<template>
  <div class="post-editor">
    <!-- 返回按钮 -->
    <div class="back-button-container">
      <el-button
        type="text"
        @click="emit('back')"
        class="back-button"
      >
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
    </div>

    <div class="editor-header">
      <div class="input-group">
        <!-- 话题搜索输入框 -->
        <div class="topic-input-container" @keydown="handleTopicKeyDown">
          <el-input
            v-model="topicQuery"
            @focus="showTopicList = true"
            @input="handleTopicSearch"
            placeholder="输入话题标签(可选)"
            class="topic-input"
          >
            <template #prefix>
              <el-icon><ChatDotRound /></el-icon>
            </template>
          </el-input>
          <!-- 话题搜索结果下拉框 -->
          <div v-if="showTopicList && filteredTopics.length > 0" class="topic-list">
            <div
              v-for="topic in filteredTopics"
              :key="topic.topic"
              @click="selectTopic(topic)"
              class="topic-item"
              :class="{ 'selected': selectedTopicIndex === filteredTopics.indexOf(topic) }"
            >
{{ topic.topic }}
</div>
</div>
        </div>
        <el-input
          v-model="title"
          placeholder="输入标题(可选)"
          class="title-input"
        />
      </div>
      <div class="mention-section">
        <div class="mention-input-container" @keydown="handleKeyDown">
          <el-input
            v-model="searchQuery"
            @focus="showUserList = true"
            @input="handleSearchInput"
            placeholder="输入学号搜索..."
            class="mention-input"
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
          <div v-if="showUserList && filteredUsers.length > 0" class="user-list">
            <div
              v-for="user in filteredUsers"
              :key="user.id"
              @click="selectUser(user)"
              class="user-item"
              :class="{ 'selected': selectedIndex === filteredUsers.indexOf(user) }"
            >
              {{ user.id }} - {{ user.username }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <div v-if="mentionedUsers.length > 0" class="mentioned-tags">
      <el-tag
        v-for="user in mentionedUsers"
        :key="user.id"
        closable
        @close="removeUser(user)"
        class="user-tag"
      >
        @{{ user.username }}({{ user.id }})
      </el-tag>
    </div>

    <div class="tinymce-container">
      <Editor
        :init="editorConfig"
        v-model="content"
      />
    </div>

    <div class="action-buttons">
      <el-button type="primary" @click="submitPost" :loading="submitting">
        发布帖子
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import 'tinymce'
import Editor from '@tinymce/tinymce-vue'

import { ElMessage } from 'element-plus'
import { User, ChatDotRound, ArrowLeft } from '@element-plus/icons-vue'
import axios from 'axios'

const props = defineProps({
  courseId: {
    type: [String, Number],
    required: true
  },
  currentUser: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['post-created', 'back'])

// 状态变量
const content = ref('')
const topic = ref('')
const topicQuery = ref('')
const title = ref('')
const mentionedUsers = ref([])
const searchQuery = ref('')
const showUserList = ref(false)
const showTopicList = ref(false)
const selectedIndex = ref(-1)
const selectedTopicIndex = ref(-1)
const submitting = ref(false)
const imageMap = ref(new Map())
const filteredUsers = ref([])
const filteredTopics = ref([])

// 话题搜索处理
async function handleTopicSearch() {
  if (!topicQuery.value.trim()) {
    filteredTopics.value = []
    return
  }

  try {
    const response = await axios.get(`/backend/api/post/topics/search/?keyword=${topicQuery.value}`, {
      withCredentials: true
    })

    if (response.data && Array.isArray(response.data)) {
      filteredTopics.value = response.data
      showTopicList.value = true
    } else {
      filteredTopics.value = []
    }
  } catch (error) {
    console.error('搜索话题失败:', error)
    ElMessage.error('搜索话题失败')
    filteredTopics.value = []
  }
}

// 选择话题
function selectTopic(selectedTopic) {
  topic.value = selectedTopic.topic
  topicQuery.value = selectedTopic.topic
  showTopicList.value = false
  selectedTopicIndex.value = -1
}

// 话题键盘导航
function handleTopicKeyDown(event) {
  if (!showTopicList.value || !filteredTopics.value.length) return

  switch (event.key) {
    case 'ArrowDown':
      event.preventDefault()
      selectedTopicIndex.value = (selectedTopicIndex.value + 1) % filteredTopics.value.length
      break
    case 'ArrowUp':
      event.preventDefault()
      selectedTopicIndex.value = selectedTopicIndex.value <= 0
          ? filteredTopics.value.length - 1
          : selectedTopicIndex.value - 1
      break
    case 'Enter':
      event.preventDefault()
      if (selectedTopicIndex.value >= 0) {
        selectTopic(filteredTopics.value[selectedTopicIndex.value])
      }
      break
    case 'Escape':
      event.preventDefault()
      showTopicList.value = false
      selectedTopicIndex.value = -1
      break
  }
}

// TinyMCE配置
const editorConfig = {
  base_url: '/tinymce',  // 添加这行
  suffix: '.min',        // 添加这行
  height: 400,
  menubar: true,
  plugins: [
    'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
    'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
    'insertdatetime', 'media', 'table', 'code', 'help', 'wordcount',
    'image imagetools'
  ],
  toolbar: 'undo redo | formatselect | bold italic backcolor | \
    alignleft aligncenter alignright alignjustify | \
    bullist numlist outdent indent | removeformat | help | \
    image media | code',
  images_upload_handler: handleImageUpload,
  automatic_uploads: true,
  images_reuse_filename: true,
  image_title: true,
  images_file_types: 'jpeg,jpg,png,gif,bmp',
  file_picker_types: 'image',
  language_url: '/tinymce/langs/zh_CN.js',
  language: 'zh_CN',
  skin: 'oxide',
  skin_url: '/tinymce/skins/ui/oxide',           // 添加这行
  content_css: '/tinymce/skins/content/default/content.css', // 添加这行
  setup: (editor) => {
    editor.on('init', () => {
      console.log('Editor initialized');
    });
  }
}

// 处理图片上传
async function handleImageUpload(blobInfo, progress) {
  return new Promise((resolve, reject) => {
    const tempUrl = `temp://${blobInfo.filename()}`
    imageMap.value.set(tempUrl, blobInfo.blob())
    resolve(tempUrl)
  })
}

// 处理学生搜索
async function handleSearchInput() {
  if (!searchQuery.value.trim()) {
    filteredUsers.value = []
    return
  }

  try {
    const response = await axios.get(`/backend/api/post/students/search/?id=${searchQuery.value}`, {
      withCredentials: true
    })

    if (response.data && Array.isArray(response.data)) {
      filteredUsers.value = response.data
      showUserList.value = true
    } else {
      filteredUsers.value = []
    }
  } catch (error) {
    console.error('搜索学生失败:', error)
    let errorMessage = '搜索学生失败'
    if (error.response && error.response.data && error.response.data.error) {
      errorMessage = error.response.data.error
    }
    ElMessage.error(errorMessage)
    filteredUsers.value = []
  }
}

// 选择学生
function selectUser(user) {
  if (user.id === props.currentUser.id) {
    ElMessage.warning('不能@自己')
    return
  }

  if (!mentionedUsers.value.some(u => u.id === user.id)) {
    mentionedUsers.value.push(user)
    const mentionText = `<span class="mention" data-student-id="${user.id}">@${user.username}(${user.id})</span> `
    content.value += mentionText
  }

  searchQuery.value = ''
  showUserList.value = false
  selectedIndex.value = -1
}

// 移除学生
function removeUser(user) {
  const index = mentionedUsers.value.findIndex(u => u.id === user.id)
  if (index > -1) {
    mentionedUsers.value.splice(index, 1)
    content.value = content.value.replace(
        `<span class="mention" data-student-id="${user.id}">@${user.username}(${user.id})</span> `,
        ''
    )
  }
}

// 提交帖子
async function submitPost() {
  if (!content.value.trim()) {
    ElMessage.warning('请输入帖子内容')
    return
  }

  submitting.value = true

  try {
    const titleContent = `<title>${title.value.trim()}</title>${content.value}`
    const formData = new FormData()
    formData.append('course_id', props.courseId)
    formData.append('content', titleContent)
    formData.append('topic', topicQuery.value)

    if (mentionedUsers.value.length > 0) {
      formData.append('mentioned_users', JSON.stringify(
          mentionedUsers.value.map(user => user.id)
      ))
    }

    for (const [tempUrl, file] of imageMap.value.entries()) {
      formData.append(`image_map[${tempUrl}]`, file)
    }

    const response = await axios.post('/backend/api/post/create/', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      withCredentials: true
    })

    ElMessage.success('帖子发布成功')
    emit('post-created', response.data)

    // 清空编辑器
    content.value = ''
    topic.value = ''
    topicQuery.value = ''
    title.value = ''
    mentionedUsers.value = []
    imageMap.value.clear()

  } catch (error) {
    console.error('发布帖子失败:', error)
    ElMessage.error(
        (error.response && error.response.data && error.response.data.error) || '发布失败，请稍后重试'
    )
  } finally {
    submitting.value = false
  }
}

// 键盘导航
function handleKeyDown(event) {
  if (!showUserList.value || !filteredUsers.value.length) return

  switch (event.key) {
    case 'ArrowDown':
      event.preventDefault()
      selectedIndex.value = (selectedIndex.value + 1) % filteredUsers.value.length
      break
    case 'ArrowUp':
      event.preventDefault()
      selectedIndex.value = selectedIndex.value <= 0
          ? filteredUsers.value.length - 1
          : selectedIndex.value - 1
      break
    case 'Enter':
      event.preventDefault()
      if (selectedIndex.value >= 0) {
        selectUser(filteredUsers.value[selectedIndex.value])
      }
      break
    case 'Escape':
      event.preventDefault()
      showUserList.value = false
      selectedIndex.value = -1
      break
  }
}

// 点击外部关闭用户列表和话题列表
function handleClickOutside(event) {
  const topicContainer = document.querySelector('.topic-input-container')
  const mentionContainer = document.querySelector('.mention-input-container')

  if (topicContainer && !topicContainer.contains(event.target)) {
    showTopicList.value = false
  }

  if (mentionContainer && !mentionContainer.contains(event.target)) {
    showUserList.value = false
  }
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.post-editor {
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.back-button-container {
  margin-bottom: 16px;
}

.back-button {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #606266;
}

.back-button:hover {
  color: #409EFF;
}

.back-button .el-icon {
  margin-right: 4px;
}

.editor-header {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.input-group {
  display: flex;
  gap: 16px;
  flex: 1;
}

.topic-input-container {
  position: relative;
  width: 200px;
}

.topic-list {
  position: absolute;
  top: 100%;
  left: 0;
  width: 100%;
  max-height: 200px;
  overflow-y: auto;
  background: white;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.topic-item {
  padding: 8px 12px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.topic-item:hover,
.topic-item.selected {
  background-color: #f5f7fa;
}

.topic-input,
.title-input {
  width: 200px;
}

.mention-section {
  position: relative;
  width: 200px;
}

.mention-input-container {
  position: relative;
}

.user-list {
  position: absolute;
  top: 100%;
  left: 0;
  width: 100%;
  max-height: 200px;
  overflow-y: auto;
  background: white;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.user-item {
  padding: 8px 12px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.user-item:hover,
.user-item.selected {
  background-color: #f5f7fa;
}

.mentioned-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 16px;
}

.user-tag {
  display: inline-flex;
  align-items: center;
}

.tinymce-container {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
}

:deep(.tox-tinymce) {
  border-radius: 4px;
}

:deep(.tox .tox-toolbar__primary) {
  background: none;
}
</style>